<template>
  <div class="pageChart">
    <div ref="echartsLine" class="impacxyone" :class="theme"></div>
    <p class="page-left" v-show="pageLeft" @click="moveLeft"><i class="iconright icon-left"></i></p><p class="page-left page-right" v-show="pageRight" @click="moveRight"><i class="iconright icon-right"></i></p>
  </div>
</template>

<script>
    import echarts from '@js/echarts.min.js';
    let myChart;
  export default {
        components: {
        },
        data () {
            return {
              pageLeft:false,
              pageRight:false,
              startX:"",
              endX:"",
            }
        },
       props: {
         type:{type:[String],default:""},
         theme:{type:[String],default:"typea"},//高度样式
         echartData: {
                         type: [Object,Array],
                         default: ()=> {
                           return {}
                         }
                      },
         pageSize:{type:[Number],default:40},/** pagesize 与 shownuber 不能相同，否则在第一页的时候出现反方向 加载数据的问题**/  //其他40、季度60、年90
         showNumber:{type:[Number],default:30},//其他30、季度50、年80
        },
        watch: {
          echartData(val, oldVal){
            this.echartsInit(this.id);
          }
        },
        created(){

        },
        mounted(){
         myChart = echarts.init(this.$refs.echartsLine)
         this.echartsInit();
         myChart.on('datazoom', (params)=> {
              let dataZoomStart = params.batch[0].start;
              var dataZoomEnd = params.batch[0].end;

              if(dataZoomEnd==100){
                  if(this.echartData.lists[0].xAxis.length==this.echartData.total){
                      this.hideOrShowButton(dataZoomStart,dataZoomEnd)
                      return false;
                  }
                  //计算图表当前一屏显示的条数
                  var now_showNumber = Math.round((dataZoomEnd - dataZoomStart)/100*this.echartData.lists[0].xAxis.length);
                  if(now_showNumber == 0){//调整显示条数计算偏差
                      now_showNumber = 1;
                  }

                  var totalsize = this.echartData.total; //数据库总条数
                  var currentsize = this.echartData.lists[0].xAxis.length; //当前已加载的条数
                  var totalPage = Math.ceil(totalsize/this.pageSize);//总页数
                  //计算下次加载的数据+当前的总数据条数
                  var presize = currentsize;
                  if(totalPage - this.echartData.pageNo == 1){
                      presize = presize + totalsize - this.echartData.pageNo*this.pageSize;
                  }else if(totalPage - this.echartData.pageNo > 1){
                      presize = presize + this.pageSize;
                  }
                  //重新计算位移量
                  var shifttemp = this.getZoomShiftByShowNumber(now_showNumber);
                  if(shifttemp > this.pageSize){//防止位移量溢出
                      shifttemp = this.pageSize;
                  }
                  this.startX = (dataZoomStart*currentsize/100 + shifttemp)/presize*100;
                  this.endX = (dataZoomEnd*currentsize/100 + shifttemp)/presize*100;

                  //***********校准x开始位置（由于滑动、缩放都会触发datazoom;故需要对x轴进行类型判断）**************
                  var lastestShowNumber = this.showNumber;
                  if(this.lastestShowNumber != null){
                      lastestShowNumber = this.lastestShowNumber;
                  }
                  //说明：在缩放(因为now_showNumber的计算可能存在误差，所以要>=2)
                  if(now_showNumber - lastestShowNumber >= 2){
                      var realshifttemp = shifttemp; //一屏显示条数，实际增量
                      if(dataZoomStart == 0){//已经在开始位置，则不需移动
                          this.startX = 0;
                      }else if(dataZoomStart > 0){
                          var leftSideNumber = Math.ceil(dataZoomStart*currentsize/100);//向上取整
                          if(leftSideNumber > realshifttemp){//左侧有隐藏数据，则计算需要滑动的位移量；
                              this.startX = (leftSideNumber - realshifttemp)/presize*100;
                              realshifttemp = 2*shifttemp;
                          }else{
                              this.startX = 0;
                              realshifttemp = leftSideNumber + shifttemp;
                          }
                      }
                      this.lastestShowNumber=now_showNumber+realshifttemp;//用于记录上一次的显示条数
                  }


                  this.$emit("onMescrollLeft");
              }else{
                  this.hideOrShowButton(dataZoomStart,dataZoomEnd)
              }
         });
        },
        methods: {
          echartsInit(){
            var _this=this;
              var datas=this.echartData;
              var echartData=datas.lists && this.echartData.lists[0] ? this.echartData.lists[0] : this.echartData;
            //var echartData={"xAxis":["2019-11-01 10:21:30","2019-11-02 09:20:47","2019-11-03 18:24:46","2019-11-04 18:10:53","2019-11-05 16:43:33","2019-11-06 15:14:13","2019-11-07 15:02:29","2019-11-08 14:49:56","2019-11-09 14:43:40","2019-11-10 14:26:08","2019-11-11 10:21:30","2019-11-12 09:20:47","2019-11-13 18:24:46","2019-11-14 18:10:53","2019-11-15 16:43:33","2019-11-16 15:14:13","2019-11-17 15:02:29","2019-11-18 14:49:56","2019-11-19 14:43:40","2019-11-20 14:26:08","2019-11-21 10:21:30","2019-11-22 09:20:47","2019-11-23 18:24:46","2019-11-24 18:10:53","2019-11-25 16:43:33","2019-11-26 15:14:13","2019-11-27 15:02:29","2019-11-28 14:49:56","2019-11-29 14:43:40","2019-11-30 14:26:08","2019-11-31 10:21:30","2019-11-32 09:20:47","2019-11-33 18:24:46","2019-11-34 18:10:53","2019-11-35 16:43:33","2019-11-36 15:14:13","2019-11-37 15:02:29","2019-11-38 14:49:56","2019-11-39 14:43:40","2019-11-40 14:26:08"],"data":[{"analysisId":991,"value":73},{"analysisId":990,"value":60},{"analysisId":970,"value":87},{"analysisId":969,"value":78},{"analysisId":935,"value":78},{"analysisId":938,"value":78},{"analysisId":940,"value":72},{"analysisId":941,"value":68},{"analysisId":942,"value":68},{"analysisId":944,"value":68},{"analysisId":991,"value":73},{"analysisId":990,"value":60},{"analysisId":970,"value":87},{"analysisId":969,"value":78},{"analysisId":935,"value":78},{"analysisId":938,"value":78},{"analysisId":940,"value":72},{"analysisId":941,"value":68},{"analysisId":942,"value":68},{"analysisId":944,"value":68},{"analysisId":991,"value":73},{"analysisId":990,"value":60},{"analysisId":970,"value":87},{"analysisId":969,"value":78},{"analysisId":935,"value":78},{"analysisId":938,"value":78},{"analysisId":940,"value":72},{"analysisId":941,"value":68},{"analysisId":942,"value":68},{"analysisId":944,"value":68},{"analysisId":991,"value":73},{"analysisId":990,"value":60},{"analysisId":970,"value":87},{"analysisId":969,"value":78},{"analysisId":935,"value":78},{"analysisId":938,"value":78},{"analysisId":940,"value":72},{"analysisId":941,"value":68},{"analysisId":942,"value":68},{"analysisId":944,"value":68}]}

            if(!Object.keys(echartData).length){
              return false;
            }

            //如果数据条数为1个，坐标标记出来，否则看不见
            var sigle_point = {};
            if(echartData.xAxis.length == 1){
              sigle_point = {data : [{name: '心率',value:echartData.data[0].value,xAxis: echartData.xAxis[0], yAxis: echartData.data[0].value}]};
            }

            var dataZoomMinSpan = 100;
            if(echartData != null){
              dataZoomMinSpan = this.getMinDataZoomScale(echartData.xAxis.length);
            }

            var dataZoomStart=this.startX ? this.startX : 0,dataZoomEnd=this.endX ? this.endX : this.showxAxisNum(echartData.xAxis.length);

            console.log("缩放比例："+dataZoomMinSpan+"===="+dataZoomStart+"==="+dataZoomEnd+"==="+echartData.xAxis.length)
            var option = {
              title: {
                text: '单位：次/分',
                textStyle:{
                  color:"#666666",
                  fontSize: 14,
                  fontWeight:"normal"
                },
                top:"8",
                left:"17"
              },
              tooltip : {
                trigger: 'axis',
                axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                  type : 'line',        // 默认为直线，可选为：'line' | 'shadow'
                  lineStyle: { // 直线指示器样式设置
                    color: '#B72B37',
                    type: 'solid',
                    width: 1,
                    opacity: 0.8
                  }
                },
                enterable:true,
                confine:true,
                position: function (point, params, dom, rect, size) {
                  // 固定在顶部
                  //return [point[0], '20%'];

                  var point=point[0],toowidth=40;
                  if(point<toowidth+10){
                    toowidth=5;
                  }else if(point+toowidth>size.viewSize[0]-toowidth){
                    toowidth=toowidth*2;
                  }
                  return [point-toowidth, '20%'];
                },
                formatter: function (params, ticket, callback) {
                  var analysisId = '';
                  var detatime="",detaildate = '';
                  var detailcolor = '';
                  var detailseries = '';
                  var heartRate = '';
                  for(var i=0;i<params.length;i++){
                    if(params[i].seriesName == '心电'){
                      analysisId = params[i].data.analysisId;
                      detatime=params[i].name;
                      var a=detatime.split(" "),b=a[0].split("-"),c=a[1].split(":");
                      detaildate = b[1]+"-"+b[2]+" "+c[0]+":"+c[1];
                      detailcolor = params[i].color;
                      detailseries = params[i].seriesName;
                      heartRate=params[i].value;
                    }
                  }
                  //赋值明细table
                  _this.$emit("onChange",{"analysisId" : analysisId,"value" : heartRate,"measureTime":detatime});
                //  assignDetails(false,[year+"-"+detaildate,heartRate],"gotoDetail('"+analysisId+"',1);");
                  //回显
                  var html="";
                  html+='<div style="width:80px;">'+detaildate+''+
                          '<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:'+detailcolor+'"></span>'+detailseries+'：'+heartRate+
                        '</div>';
                  ;
                  return html;
                }
              },
              legend: {
                show:true,
                data:['心电', {name:"正常区间",icon:'image://'}],
                top:"8",
                right:'12',
                textStyle:{
                  color:"#666666",
                  fontWeight:"normal"
                },
                selectedMode:false
              },
              grid: {
                left: '35',
                right: '35',
                top:'40',
                bottom:'20',
                containLabel: true
              },
              xAxis :{
                type : 'category',
                splitLine: { show: false },
                boundaryGap: true,
                inverse : true,
                data :echartData.xAxis,
                axisLabel:{
                  formatter:function(xVal){
                    var x=xVal.split(" ")[0].split("-")/*,ddd=xVal.split(" ")[1].split(":")*/;
                    return x[1]+"-"+x[2];
                  },
                  fontSize:"13",
                  color:"#999999"
                },
                axisLine:{
                  lineStyle:{
                    width:'0.5',
                    color:"#B3B3B3"
                  }
                },
                axisTick:{
                  show:false
                }
              },
              yAxis : {
                type : 'value',
                splitLine: { show: false },
                position:'right',
                axisLine:{
                  lineStyle:{
                    width:'0.5',
                    color:"#B3B3B3"
                  }
                },
                axisTick:{
                  show:false
                },
                axisLabel: {
                  formatter: ''
                },
                min:20,
                max:180
              },
              dataZoom: [
                {
                  type: 'inside',
                  minSpan : dataZoomMinSpan,
                  start: dataZoomStart,
                  end: dataZoomEnd
                }
              ],
              series : [
                {
                  name:'心电',
                  type: 'line',
                  symbol : "circle",
                  symbolSize : 10,
                  showAllSymbol: true,
                  smooth: false,
                  data:echartData.data,
                  markPoint: sigle_point,
                  markArea: {
                    silent : true,
                    show:true,
                    itemStyle:{
                      normal:{
                        color: "#F4F9F0",
                        opacity: '1'
                      }
                    },
                    data: [ [{
                      yAxis: 60
                    }, {
                      yAxis: 100
                    }] ]
                  },
                  lineStyle:{
                    normal:{
                      color: "#5ac2ca",
                      width:'2'
                    }
                  },
                  itemStyle:{
                    normal:{
                      color: "#5ac2ca",
                      opacity: '1'
                    }
                  },
                  markLine:  {
                    silent:true,
                    show:true,
                    animation:false,
                    symbol:'none',
                    lineStyle: {
                      normal: {
                        type: 'solid',
                        color: "#D7D7D7",
                        width:'0.5'
                      }
                    },
                    tooltip: {
                      formatter: ''
                    },
                    data:[
                      {
                        xAxis: 0,
                        yAxis: 100,
                        label: {
                          normal: {
                            formatter: 100,
                            position:'start'
                          }
                        }
                      },
                      {
                        xAxis: 0,
                        yAxis: 60,
                        label: {
                          normal: {
                            formatter: 60,
                            position:'start'
                          }
                        }
                      }
                    ]
                  }
                },
                {
                  name: '正常区间',
                  type: 'bar',
                  data: []
                }
              ]
            };
            myChart.setOption(option);
            window.onresize = function(){
              myChart.resize();
            }
            myChart.dispatchAction({
              type: 'showTip',
              seriesIndex: 0,
              dataIndex: 0
            });
            _this.hideOrShowButton(dataZoomStart,dataZoomEnd);

          },
          /**
           * 按钮操作：向左移动
           */
          moveLeft(){
           //------隐藏tootip,在左右移动需要隐藏tooltip---start----
            myChart.dispatchAction({
              type: 'hideTip'
            });
            myChart.dispatchAction({
              type: 'updateAxisPointer',
              currTrigger: 'leave'
            });
            //------隐藏tootip,在左右移动需要隐藏tooltip---end------
            var startScale = myChart.getOption().dataZoom[0].start;
            var endScale = myChart.getOption().dataZoom[0].end;
            //定位x轴开始、结束为止坐标
            var now_showNumber = Math.round((endScale - startScale)/100*this.echartData.lists[0].xAxis.length);
            if(now_showNumber == 0){//调整显示条数计算偏差
              now_showNumber = 1;
            }
            var totalsize = this.echartData.total; //数据库总条数
            var currentsize = this.echartData.lists[0].xAxis.length; //当前已加载的条数
            var totalPage = Math.ceil(totalsize/this.pageSize);//总页数
            if(endScale + now_showNumber/currentsize*100 >= 100){ //可能需要加载下一页数据
              if(totalsize > currentsize){//需要加载
                //计算下次加载的数据+当前的总数据条数
                var presize = currentsize;//预加载后的条数（默认值为当前条数）
                if(totalPage - this.echartData.pageNo == 1){
                  presize = presize + totalsize - this.echartData.pageNo*this.pageSize;
                }else if(totalPage - this.echartData.pageNo > 1){
                  presize = presize + this.pageSize;
                }
                //计算x轴的起始位置、结束位置
                this.startX = (startScale*currentsize/100 + presize - currentsize)/presize*100;
                this.endX = (endScale*currentsize/100 + presize - currentsize)/presize*100;
                //执行方法
                this.$emit("onMoveLeft");
              }else{//已经加载完
                var x_start = 100 - now_showNumber/currentsize*100;
                var x_end = 100;
                //执行方法
                /*if(aftfn != undefined && aftfn != null){
                  aftfn(x_start,x_end);
                }*/
                this.startX = x_start;
                this.endX =x_end;
                this.echartsInit();
                //是否显示左右按钮
                this.hideOrShowButton(x_start,x_end);
              }
            }else{//直接滑动已有数据
              //计算x轴的起始位置、结束位置
              var x_start = startScale + now_showNumber/currentsize*100;
              var x_end = endScale + now_showNumber/currentsize*100;
              //执行方法
              /*if(aftfn != undefined && aftfn != null){
                aftfn(x_start,x_end);
              }*/
              this.startX = x_start;
              this.endX =x_end;
              this.echartsInit();
              //是否显示左右按钮
              this.hideOrShowButton(x_start,x_end);
            }
          },
          /**
           * 按钮操作：向右移动
           */
          moveRight(){
            //------隐藏tootip,在左右移动需要隐藏tooltip---start----
            myChart.dispatchAction({
              type: 'hideTip'
            });
            myChart.dispatchAction({
              type: 'updateAxisPointer',
              currTrigger: 'leave'
            });
            //------隐藏tootip,在左右移动需要隐藏tooltip---end------
            var startScale = myChart.getOption().dataZoom[0].start;
            var endScale = myChart.getOption().dataZoom[0].end;
            //定位x轴开始、结束为止坐标
            var now_showNumber = Math.round((endScale - startScale)/100*this.echartData.lists[0].xAxis.length);
            if(now_showNumber == 0){//调整显示条数计算偏差
              now_showNumber = 1;
            }
            var currentsize = this.echartData.lists[0].xAxis.length; //当前已加载的条数
            var x_start;
            var x_end;
            if(startScale - now_showNumber/currentsize*100 < 0){
              x_start = 0;
              x_end = now_showNumber/currentsize*100;
            }else{
              x_start = startScale - now_showNumber/currentsize*100;
              x_end = endScale - now_showNumber/currentsize*100;
            }
            this.startX = x_start;
            this.endX =x_end;
            //执行方法
            /*if(aftfn != undefined && aftfn != null){
              aftfn(x_start,x_end);
            }*/
            this.echartsInit();
            //是否显示左右按钮
            this.hideOrShowButton(x_start,x_end);
          },
          /**
           * 是否显示左右按钮
           */
          hideOrShowButton(start,end){
            if(start>0){
              this.pageRight=true;
            }else{
              this.pageRight=false;
            }

            if(end<100){
              this.pageLeft=true;
            }else{
              this.pageLeft=false;
            }
          },
          //加载完数据，计算需要滑动位移量
          getZoomShiftByShowNumber(number){
              if(number >= 20){ //三个位移量
                  return 3;
              }else if(number >= 5){//两个位移量
                  return 2;
              }else if(number < 5){//一个位移量
                  return 1;
              }
              return 1;
          },
          //计算datazoom最小缩放比例
         getMinDataZoomScale(length){
              if(length <= 5){
                return 100;
              }else{
                return Math.ceil(5/length*100);
              }
         },
          //图表x轴显示范围%计算
         showxAxisNum(length){
            if(this.showNumber>=length){
              return 100;
            }else{
              return Math.ceil(this.showNumber/length*100);
            }
         }
        }
    }
</script>
<style lang="scss" scoped>
.pageChart{
  position: relative;
  .page-left{
    position: absolute;
    top: 50%;
    left: 0rem;
    margin-top:px2rem(-120px);
    background: rgba(84, 181, 189, 0.35);
    /* background: #9ED0D4;opacity:0.5;*/
    color: #FFFFFF;
    width: px2rem(135px);
    height: px2rem(240px);
    line-height: px2rem(120px);
    padding: 0rem 0rem 0rem 0rem;opacity:1;
    text-align: center;
    z-index: 1;
    &.page-right{
      left: auto;
      right: 0rem !important;
    }
    .icon-left{
      &:after{
        width: px2rem(35px);
        height: px2rem(35px);
        border-color:#ffffff;
        right: px2rem(45px);
        margin-top: px2rem(-15.5px);
        transform:rotate(225deg);
      }
    }
    .icon-right{
      &:after{
        width: px2rem(35px);
        height: px2rem(35px);
        border-color:#ffffff;
        right: px2rem(65px);
        margin-top: px2rem(-15.5px);
      }
    }
    span{
      display: inline-block;
      width: px2rem(60px);
      line-height:px2rem(50px);
      vertical-align: middle;
      margin-top: px2rem(20px);
      font-size: px2rem(42px)
    }

  }

}
.impacxyone{
   background:#ffffff;
   padding:px2rem(20px) 0px px2rem(0px) 0px;
   &.typea{
    height: px2rem(630px);
   }
}

</style>
